﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Web;
namespace NewsExtractor
{
    public class VnexpressClass : ToBaoInterface
    {
        // Physical path of directory where files to saved in
        string _Path;
        //Directory's name
        string _Name = "vnexpress";
        //File contains category
        //Structure of this file:

        // <Category><URL><Name of XML File>
        // For example:
        //      Tổng hợp|http://vnexpress.net/tonghop|tonghop
        //      Thể thao|http://vnexpress.net/thethao|thethao
        string _CategoryFile = "category.txt";

        //Category file, client recieve
        string _CategoryXML = "category.xml";

        //List parsed from _CategoryFile
        //Name | RSS path | ID
        List<string[]> _listCaregory;


        #region Methods
        //Constructor
        public VnexpressClass(string rootPath)
        {
            _Path = rootPath + "vnexpress/";
            if (!Directory.Exists(_Path))
                Directory.CreateDirectory(_Path);
            _listCaregory = new List<string[]>();
            UpdateListCategory();
            //UpdateCategoryXML();
            // UpdateBaiBao();

        }

        //Load CategoryFile to _listCategory
        public void UpdateListCategory()
        {
            try
            {
                _listCaregory.Clear();
                FileStream _file = new FileStream(_Path + _CategoryFile, FileMode.Open);
                StreamReader rd = new StreamReader(_file);
                while (!rd.EndOfStream)
                {
                    string line = rd.ReadLine();
                    string[] array = line.Split('|');
                    _listCaregory.Add(array);
                }
                rd.Close();
                _file.Close();
            }
            catch
            {
            }
        }

        //Get Rss bai bao from vnexpress to Server
        public void UpdateRSSBaiBaos()
        {
            try
            {
                XmlTextReader rssReader;
                XmlDocument doc = new XmlDocument();

                foreach (string[] item in _listCaregory)
                {
                    rssReader = new XmlTextReader(item[1]);
                    doc.Load(rssReader);
                    doc.Save(_Path + item[2] + ".rss");
                }
            }
            catch
            {

            }

        }
        //Get Full bai bao from vnexpress to Server
        public void UpdateFullBaiBaos()
        {
            foreach (string[] item in _listCaregory)
            {
                string chuyen_muc_content = getChuyenMucString_RSS(item[2]);
                List<BaiBao> listBaiBao = HttpUtil.getListBaiBaoFromRSS(chuyen_muc_content);
                foreach (BaiBao curBaiBao in listBaiBao)
                {
                    XmlDocument xmlDoc = new XmlDocument();

                    // Write down the XML declaration
                    XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

                    // Create the root element
                    XmlElement rootNode = xmlDoc.CreateElement("BaiBao");
                    
                    XmlElement curNode = xmlDoc.CreateElement("title");
                    curNode.InnerText = curBaiBao.TieuDe;
                    rootNode.AppendChild(curNode);

                    curNode = xmlDoc.CreateElement("link");
                    curNode.InnerText = curBaiBao.URL;
                    rootNode.AppendChild(curNode);

                    curNode = xmlDoc.CreateElement("des");
                    curNode.InnerText = curBaiBao.MoTa;
                    rootNode.AppendChild(curNode);

                    curNode = xmlDoc.CreateElement("content");
                    curNode.InnerText = curBaiBao.NoiDung;
                    rootNode.AppendChild(curNode);

                    xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
                    xmlDoc.AppendChild(rootNode);

                    string fileName = Utility.CleanURL(curBaiBao.URL);
                    xmlDoc.Save(_Path + fileName + ".xml");                
                }
            }
        }

        ////Get Rss & Full bai bao from vnexpress to Server
        public void UpdateBaiBao()
        {
            try
            {

                UpdateRSSBaiBaos();
                UpdateFullBaiBaos();
            }
            catch
            {

            }
        }

        //Update Category XML file to send to client
        private void UpdateCategoryXML()
        {
            XmlTextWriter xmlWr = new XmlTextWriter(_Path + _CategoryXML, Encoding.UTF8);
            xmlWr.WriteStartDocument();
            xmlWr.WriteStartElement("Categories");
            xmlWr.WriteAttributeString("Website", _Name);
            if (!File.Exists(_Path + _CategoryFile))
                UpdateListCategory();
            foreach (string[] item in _listCaregory)
            {
                xmlWr.WriteStartElement("Category");
                xmlWr.WriteElementString("Name", item[0]);
                xmlWr.WriteStartElement("URL");
                xmlWr.WriteCData("Category.aspx?website=" + _Name + "&category=" + item[2]);
                xmlWr.WriteEndElement();
                xmlWr.WriteEndElement();
            }
            xmlWr.WriteEndElement();
            xmlWr.WriteEndDocument();
            xmlWr.Close();
        }

        /// <summary>
        /// Get all Chuyen Muc in this newspaper (return to client)
        /// </summary>
        /// 
        public string getCategoryList()
        {
            if (!File.Exists(_Path + _CategoryXML))
                UpdateCategoryXML();
            TextReader rd = new StreamReader(_Path + _CategoryXML);
            string result = rd.ReadToEnd();
            rd.Close();
            return result;

        }

        /// <summary>
        /// Get all Bai Bao in a given Chuyen Muc
        /// </summary>
        /// <param name="curChuyenMuc">The Chuyen Muc needs getting list of Bai Bao</param>
        public string getChuyenMucString_RSS(string curChuyenMuc)
        {
            if (File.Exists(_Path + curChuyenMuc + ".rss"))
            {
                TextReader rd = new StreamReader(_Path + curChuyenMuc + ".rss");
                string result = rd.ReadToEnd();
                rd.Close();
                return result;
            }

            return "";
        }

        //Get Newspaper's name
        public string getName()
        {
            return _Name;
        }

        #endregion
    }
}
